﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IEWebSite.Administration
{
    public partial class DBFileDownloader : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.QueryString.AllKeys.Contains("id") || !Request.QueryString.AllKeys.Contains("table") || !Request.QueryString.AllKeys.Contains("column"))
            {
                //Response.Redirect("~/Error.aspx");
                return;
            }

            string requestTable = Request.QueryString["table"];
            string requestColumn = Request.QueryString["column"];
            Int32 requestId = Int32.Parse(Request.QueryString["id"]);

            System.Data.SqlClient.SqlDataReader sqlDataReader = null;
            System.Data.SqlClient.SqlConnection conn = null;
            System.Data.SqlClient.SqlCommand selcmd = null;
            try
            {
                conn = Utils.GetSqlConnection();
                selcmd = new System.Data.SqlClient.SqlCommand("select " + requestColumn + ", " + requestColumn + "MimeType FROM "+requestTable+" WHERE Id"+requestTable+"="+requestId, conn);
                conn.Open();
                sqlDataReader = selcmd.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    Response.Clear();
                    Response.ContentType = sqlDataReader[requestColumn+"MimeType"].ToString();
                    Response.BinaryWrite((byte[])sqlDataReader[requestColumn]);
                }
                if (sqlDataReader != null) sqlDataReader.Close();
            }
            catch (Exception ex)
            {
               // Session["ErrorText"] = ex.Message;
               // Response.Redirect("~/Error.aspx");
            }
            finally
            {
                if (conn != null) conn.Close();
            }

        }
    }
}
